<script setup lang="ts">
import { ref, onMounted } from "vue";
import { message } from "ant-design-vue";
import { DatabaseOutlined } from "@ant-design/icons-vue";
import {
  listEquipmentDataByPage,
  addEquipmentData,
  updateEquipmentData,
  deleteEquipmentData,
  payEquipmentData,
} from "@/api/equipmentData";
import type {
  EquipmentData,
  EquipmentDataQueryRequest,
  EquipmentDataAddRequest,
  EquipmentDataUpdateRequest,
  PayRequest,
} from "@/models/equipmentData";
import dayjs from "dayjs";

// 设备数据管理相关状态
const equipmentDatas = ref<EquipmentData[]>([]);
const equipmentDataTotal = ref(0);
const equipmentDataCurrentPage = ref(1);
const equipmentDataPageSize = ref(6);
const equipmentIdSearch = ref("");
const equipmentDataLoading = ref(false);

// 设备数据编辑弹窗
const equipmentDataModalVisible = ref(false);
const equipmentDataModalTitle = ref("添加设备数据");
const editingEquipmentData = ref<EquipmentDataUpdateRequest>({
  dataId: 0,
  equipmentId: 0,
  readValue: 0,
  equipmentBalance: 0,
});

// 缴费弹窗
const payModalVisible = ref(false);
const payingEquipmentId = ref(0);
const payAmount = ref(0);

// 获取设备数据列表
const fetchEquipmentDatas = async () => {
  equipmentDataLoading.value = true;
  try {
    const queryRequest: EquipmentDataQueryRequest = {
      current: equipmentDataCurrentPage.value,
      pageSize: equipmentDataPageSize.value,
      equipmentId: equipmentIdSearch.value
        ? parseInt(equipmentIdSearch.value)
        : undefined,
    };
    const res = await listEquipmentDataByPage(queryRequest);
    if (res.data.code === 0) {
      equipmentDatas.value = res.data.data.records;
      equipmentDataTotal.value = res.data.data.total;
    } else {
      message.error("获取设备数据列表失败");
    }
  } catch (error) {
    message.error("获取设备数据列表失败");
  } finally {
    equipmentDataLoading.value = false;
  }
};

// 搜索设备数据
const onSearch = () => {
  equipmentDataCurrentPage.value = 1;
  fetchEquipmentDatas();
};

// 重置搜索
const handleReset = () => {
  equipmentIdSearch.value = "";
  equipmentDataCurrentPage.value = 1;
  fetchEquipmentDatas();
};

// 处理分页变化
const handleEquipmentDataTableChange = (pagination: any) => {
  equipmentDataCurrentPage.value = pagination.current;
  equipmentDataPageSize.value = pagination.pageSize;
  fetchEquipmentDatas();
};

// 添加设备数据
const handleAddEquipmentData = () => {
  equipmentDataModalTitle.value = "添加设备数据";
  editingEquipmentData.value = {
    dataId: 0,
    equipmentId: 0,
    readValue: 0,
    equipmentBalance: 0,
  };
  equipmentDataModalVisible.value = true;
};

// 编辑设备数据
const handleEditEquipmentData = (record: EquipmentData) => {
  equipmentDataModalTitle.value = "编辑设备数据";
  editingEquipmentData.value = {
    dataId: record.dataId,
    equipmentId: record.equipmentId,
    readValue: record.readValue,
    equipmentBalance: record.equipmentBalance,
  };
  equipmentDataModalVisible.value = true;
};

// 打开缴费弹窗
const handleOpenPayModal = (record: EquipmentData) => {
  payingEquipmentId.value = record.equipmentId;
  payAmount.value = 0;
  payModalVisible.value = true;
};

// 处理缴费
const handlePay = async () => {
  try {
    if (payAmount.value <= 0) {
      message.error("请输入有效的缴费金额");
      return;
    }

    const payRequest: PayRequest = {
      money: payAmount.value,
      equipmentId: payingEquipmentId.value,
    };

    const res = await payEquipmentData(payRequest);
    if (res.data.code === 0) {
      message.success("缴费成功");
      payModalVisible.value = false;
      fetchEquipmentDatas();
    } else {
      message.error(res.data.message || "缴费失败");
    }
  } catch (error) {
    message.error("缴费失败");
  }
};

// 保存设备数据
const handleSaveEquipmentData = async () => {
  try {
    if (editingEquipmentData.value.equipmentId === 0) {
      message.error("请填写完整信息");
      return;
    }

    if (editingEquipmentData.value.dataId === 0) {
      // 添加设备数据
      const res = await addEquipmentData(editingEquipmentData.value);
      if (res.data.code === 0) {
        message.success("添加成功");
      } else {
        message.error(res.data.message || "添加失败");
      }
    } else {
      // 更新设备数据
      const res = await updateEquipmentData(editingEquipmentData.value);
      if (res.data.code === 0) {
        message.success("更新成功");
      } else {
        message.error(res.data.message || "更新失败");
      }
    }
    equipmentDataModalVisible.value = false;
    fetchEquipmentDatas();
  } catch (error) {
    message.error("操作失败");
  }
};

// 删除设备数据
const handleDeleteEquipmentData = async (record: EquipmentData) => {
  try {
    const res = await deleteEquipmentData(record.dataId);
    if (res.data.code === 0) {
      message.success("删除成功");
      fetchEquipmentDatas();
    } else {
      message.error(res.data.message || "删除失败");
    }
  } catch (error) {
    message.error("删除失败");
  }
};

onMounted(() => {
  fetchEquipmentDatas();
});
</script>

<template>
  <a-card class="info-card">
    <template #title>
      <div class="card-title">
        <database-outlined />
        <span>设备数据管理</span>
      </div>
    </template>
    <template #extra>
      <a-space>
        <a-input
          v-model:value="equipmentIdSearch"
          placeholder="设备ID"
          style="width: 150px"
          @pressEnter="onSearch"
        />
        <a-button type="primary" @click="onSearch">搜索</a-button>
        <a-button @click="handleReset">重置</a-button>
        <a-button type="primary" @click="handleAddEquipmentData">
          添加数据
        </a-button>
      </a-space>
    </template>

    <a-table
      :dataSource="equipmentDatas"
      :loading="equipmentDataLoading"
      :pagination="{
        total: equipmentDataTotal,
        current: equipmentDataCurrentPage,
        pageSize: equipmentDataPageSize,
        showSizeChanger: true,
        showQuickJumper: true,
      }"
      @change="handleEquipmentDataTableChange"
    >
      <a-table-column key="dataId" title="数据ID" data-index="dataId" />
      <a-table-column
        key="equipmentId"
        title="设备ID"
        data-index="equipmentId"
      />
      <a-table-column key="readValue" title="读数" data-index="readValue" />
      <a-table-column
        key="equipmentBalance"
        title="余额"
        data-index="equipmentBalance"
      />
      <a-table-column
        key="createTime"
        title="创建时间"
        data-index="createTime"
        :customRender="({ text }: { text: string }) =>
          dayjs(text).format('YYYY-MM-DD HH:mm:ss')
        "
      />
      <a-table-column key="action" title="操作">
        <template #default="{ record }">
          <a-space>
            <a @click="handleEditEquipmentData(record)">编辑</a>
            <a-divider type="vertical" />
            <a @click="handleOpenPayModal(record)">缴费</a>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条数据吗？"
              @confirm="handleDeleteEquipmentData(record)"
            >
              <a style="color: #ff4d4f">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table-column>
    </a-table>

    <!-- 设备数据编辑弹窗 -->
    <a-modal
      v-model:visible="equipmentDataModalVisible"
      :title="equipmentDataModalTitle"
      @ok="handleSaveEquipmentData"
    >
      <a-form :model="editingEquipmentData" layout="vertical">
        <a-form-item label="设备ID" required>
          <a-input-number
            v-model:value="editingEquipmentData.equipmentId"
            style="width: 100%"
            :min="1"
          />
        </a-form-item>
        <a-form-item label="读数" required>
          <a-input-number
            v-model:value="editingEquipmentData.readValue"
            style="width: 100%"
            :min="0"
            :step="0.01"
          />
        </a-form-item>
        <a-form-item label="余额" required>
          <a-input-number
            v-model:value="editingEquipmentData.equipmentBalance"
            style="width: 100%"
            :min="0"
            :step="0.01"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 缴费弹窗 -->
    <a-modal v-model:visible="payModalVisible" title="缴费" @ok="handlePay">
      <a-form layout="vertical">
        <a-form-item label="缴费金额" required>
          <a-input-number
            v-model:value="payAmount"
            style="width: 100%"
            :min="0"
            :step="0.01"
            prefix="￥"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<style scoped>
.info-card {
  margin-bottom: 24px;
}

.card-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  color: #1f1f1f;
}

.card-title .anticon {
  margin-right: 12px;
  font-size: 20px;
  color: #1890ff;
}
</style>
